﻿using BootstrapBlazor.Components;
using Common.Api.Dtos;
using Cyss.Core;
using Cyss.Core.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Pages.Manager.Settings
{
    public class Edit : ComponentBase
    {
        /// <summary>
        /// 类型
        /// </summary>
        [Parameter]
        public SettingTypeModel SettingType { set; get; } = new SettingTypeModel();

        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            if (this.SettingType == null || string.IsNullOrWhiteSpace(this.SettingType.TypeName))
            {
                base.BuildRenderTree(builder);
                return;
            }

            var type = GetFixedComponentTypes().FirstOrDefault(x => x.Name == this.SettingType.TypeName);
            if (type != null)
            {
                var settingComponent = GetSettingComponent(type);
                builder.AddContent(0, settingComponent.Render());
                base.BuildRenderTree(builder);
            }
            else
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add(nameof(SettingDynamicTemplate.SettingType), SettingType);
                var component = BootstrapDynamicComponent.CreateComponent<SettingDynamicTemplate>(parameters);
                builder.AddContent(0, component.Render());
                base.BuildRenderTree(builder);
            }
        }

        /// <summary>
        /// 生成页面
        /// </summary>
        /// <returns></returns>
        private BootstrapDynamicComponent GetSettingComponent<T>() where T : IComponent
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add(nameof(BaseSettingComponent<BaseSettingModel>.SettingType), SettingType);
            return BootstrapDynamicComponent.CreateComponent<T>(parameters);
        }

        /// <summary>
        /// 生成页面
        /// </summary>
        /// <returns></returns>
        private BootstrapDynamicComponent GetSettingComponent(Type type)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add(nameof(BaseSettingComponent<BaseSettingModel>.SettingType), SettingType);
            return new BootstrapDynamicComponent(type, parameters);
        }

        /// <summary>
        /// 固定模板类型集合
        /// </summary>
        /// <returns></returns>
        private List<Type> GetFixedComponentTypes()
        {
            List<Type> componentTypes = new List<Type>();
            componentTypes.Add(typeof(UpsSetting));
            return componentTypes;
        }

    }
}
